#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>

int main()
{
    //fd[0]是读端fd[1]是写端
    int fd[2] = {0};
    if(pipe(fd) < 0)
    {
        perror("pipe");
        return 1;
    }
    pid_t id = fork();
    if(id == 0)
    {
        close(fd[0]);
        const char* msg = "hello father,i am child.......";
        int count = 10;
        while(count--)
        {
            write(fd[1],msg,strlen(msg));
            sleep(1);
        }
        close(fd[1]);
        exit(0);
    }
    //父进程关闭写端，然后读取管道数据并输出
    close(fd[1]);
    char buff[64];
    while(1)
    {
        ssize_t s = read(fd[0],buff,sizeof(buff));
        if(s > 0)
        {
            //说明有数据
            buff[s] = '\0';
            printf("child send to father:%s\n",buff);
        }
        else if(s == 0)
        {
            //说明文件读取完毕，后续没有
            printf("read file end\n");
            break;
        }
        else 
        {
            printf("read error\n");
            break;
        }
    }
    //父进程
    
    close(fd[0]);//父进程关闭读端，子进程直接被系统干掉（看状态码）。
    int status = 0;
    waitpid(id,&status,0);
    return 0;
}